append_path () {
  case ":$PATH:" in
    *:"$1":*)
      ;;
    *)
    PATH="${PATH:+$PATH:}$1"
  esac
}

append_path '/util'
append_path '/util/lib'

alias p='pacman'
alias pi='pacman -Syy'
alias py='pacman -Syy --noconfirm'
alias ps='pacman -Ss'

export KUBECONFIG=/etc/rancher/rke2/rke2.yaml
export NVM_NODEJS_ORG_MIRROR=https://npm.taobao.org/mirrors/node/
export NVM_IOJS_ORG_MIRROR=http://npm.taobao.org/mirrors/iojs


alias e='exa -abghHlS --octal-permissions --time-style=long-iso'

# common alias
export no_proxy='10.94.0.0/16,11.169.0.0/16,10.43.0.0/16,10.42.0.0/16,localhost,127.0.0.1'

alias f=fuck
alias updateenv='curl -H "cache-control:no-cache" -sfL https://gitee.com/calfenyin/public/raw/master/envsetup/res/setup.sh | sh -'

alias rr='cat /etc/*release*'
alias psg='ps -ef|grep -i'

alias k=kubectl
alias kc='kubectl'
alias kk='kubectl kustomize'
alias kd='crictl'
alias ccl='crictl'

alias pods='kc get pods -A -o wide'
alias nodes='kc get nodes -o wide'
alias apply='kc apply -f'
alias applyk='kc apply -k'
alias replace='kc replace -f'
alias dk='docker'

alias g=git
alias gs='git status'
alias gpu='git push'
alias tf='tail -f -n 100'
alias grep='grep -i --color=auto --exclude-dir={.bzr,CVS,.git,.hg,.svn,.idea,.tox}'
alias grp='grep -i'

alias xgz='tar xzf'
#alias cgz='tar czf'
alias xbz='tar xjvf'
alias vi=vim
alias svi='vim'
alias svim='vim'

alias ff='find . -iname'
alias fa='find / -iname'

alias strg='grep -i -rn'

alias sc='systemctl'
alias scu='systemctl --user'

alias scl='systemctl daemon-reload'
alias sclu='systemctl --user daemon-reload'

alias tsl='journalctl -f -u' # tail service log

alias pip='python3.8 -m pip'
alias scs='systemctl status'

alias curli='curl -k'
alias curld='curl -kv --noproxy "*"'
alias wgeti='wget --no-check-certificate'

alias si='sudo -i'

alias clusterkey='cat /ehc/rancher/rke2/server/token'
function clusterconf() {
  if [[ "$#" -eq 0 ]]; then
    echo usage: clusterconf clustername
    return
  fi

  local name=$1
  local host_ip=$(hostname -I|awk '{print $1}')
  cat /etc/rancher/rke2/rke2.yaml | sed "s/127.0.0.1/$host_ip/" | sed  "11s/.*/  name: $name/" |  sed  "12s/.*/current-context: $name/"
}

function kcdecode () {
  kubectl -n $1  get secret $2 -o jsonpath='{.data}' | jq -r .$3 | base64 -d
}

function bsf() {
  echo -n "$1" | base64 -w 0
}

function bsfd() {
  echo -n "$1" | base64 -d
}

function force_remove_ns {
  NS=`kubectl get ns |grep Terminating | awk 'NR==1 {print $1}'` && kubectl get namespace "$NS" -o json   | tr -d "\n" | sed "s/\"finalizers\": \[[^]]\+\]/\"finalizers\": []/"   | kubectl replace --raw /api/v1/namespaces/$NS/finalize -f - > /dev/null 2>&1 | echo successfully deleted ns: $NS
}

export PATH=$PATH:/util:/usr/local/bin
setup_color() {
  # Only use colors if connected to a terminal
  if [ -t 1 ]; then
    RED=$(printf '\033[31m')
    GREEN=$(printf '\033[32m')
    YELLOW=$(printf '\033[33m')
    BLUE=$(printf '\033[34m')
    BOLD=$(printf '\033[1m')
    RESET=$(printf '\033[m')
  else
    RED=""
    GREEN=""
    YELLOW=""
    BLUE=""
    BOLD=""
    RESET=""
  fi
}

function setimage() {
  ns=$1
  deploy=$2
  image=$3
  kubectl -n $ns patch deployment $deploy --patch "{\"spec\": {\"template\": {\"spec\": {\"containers\": [{\"name\": \"$deploy\",\"image\": \"$image\"}]}}}}"
}

function getimage() {
  ns=$1
  deploy=$2

  #kubectl -n $ns get deploy $deploy -o jsonpath='{range .items[*]}{.metadata.name}: {.spec.template.spec.containers[0].image}{"\n"}' | sed '$d' | grep -v klipper-lb
  kubectl -n $ns get deploy $deploy -o=custom-columns='Name:metadata.name,Image:spec.template.spec.containers[0].image'
}

expose_service () {
  if [[ "$#" -ne 3  ]]; then
    echo usage: expose_service namespace deploy port
    return 1
  fi

  ns=$1
  deploy=$2
  port=$3

  if ! kubectl -n $ns get svc $deploy >/dev/null 2>&1; then kubectl -n $ns expose deployment $deploy --port=$port --target-port=$port; fi
}

gethpa() {
  if [[ "$#" -ne 2  ]]; then
    echo usage: gethpa namespace deploy
    return 1
  fi

  ns=$1
  deploy=$2

  kubectl -n $ns get hpa $deploy
}

sethpa () {
  if [[ "$#" -ne 4  ]]; then
    echo usage: sethpa namespace deploy minReplicas maxReplicas
    return 1
  fi

  ns=$1
  deploy=$2
  minReplicas=$3
  maxReplicas=$4

  hpaTemplate="
    apiVersion: autoscaling/v2beta2
    kind: HorizontalPodAutoscaler
    metadata:
      name: [DEST_NAME]
      namespace: $ns
    spec:
      scaleTargetRef:
        kind: Deployment
        name: [DEST_NAME]
        apiVersion: apps/v1
      minReplicas: $minReplicas
      maxReplicas: $maxReplicas
      metrics:
        - type: Resource
          resource:
            name: cpu
            target:
              type: AverageValue
              averageValue : 500m
        - type: Resource
          resource:
            name: memory
            target:
              type: AverageValue
              averageValue: 500Mi
"
  echo "$hpaTemplate" |sed "s/\[DEST_NAME\]/$deploy/" | kubectl -n $ns apply -f -
}

alias deploy='/rke2/deploy.sh'

function restartdeploy() {
  if [ "$#" -ne 2 ]; then
    echo usage: restartdeploy namespace deploy
    return
  fi

  ns=$1
  deploy=$2

  kc -n $ns rollout restart deploy $deploy
}

function pod() {
  setup_color
  if [ "$1" = "debug" ]; then
    kc run -i --tty --overrides='{"spec": { "nodeSelector": {"kubernetes.io/os": "linux"}}}' --image ars.adponehr.com/rancher/debugger debug-pod --restart=Never --rm -- /bin/sh
    return
  fi

  podIndex="$3"
  [[ "$3" == "" ]] && podIndex=1
  base=`kc get pods -A -o wide`

  # try find the line which match search regex, return linenumber:podname
  temp=`echo "$base" | awk '{print $2}' | grep -ne $2 | awk -v "podIndex=$podIndex" 'NR==podIndex{print $1}'`

  linenumber=`echo "$temp" | cut -d : -f 1`
  podname=`echo "$temp" | cut -d : -f 2`

  nodename=`echo "$base" | awk -v "linenumber=$linenumber" 'NR==linenumber{print $8}'`
  ns=`echo "$base" | awk -v "linenumber=$linenumber" 'NR==linenumber{print $1}'`

  if [ "$podname" = "" ]; then
    echo pod not found
    return 1
  fi

  if [[ "$1" != "g" && "$1" != "get" ]]; then
    echo "working on pod ${YELLOW}$podname${RESET} in namespace ${YELLOW}$ns${RESET} on node ${YELLOW}$nodename${RESET}"

    shellname=`ps -p $$ --no-headers -o comm=`
    if [ "$shellname" = "zsh" ]; then
      read -s -k '?Press any key to continue...'
    else
      # bash
      read -n1 -p  'Press any key to continue...'
    fi

    echo .
  fi

  case "$1" in
    'exec'|'x')
      cmd=$4
      kc -n $ns exec -i -t $podname -- sh -c "(bash || sh || ash)"
      return
      ;;
    'd' |'delete')
      op="delete"
      ;;
    'g' | 'get')
      echo $base | awk 'NR==1' # show header
      echo $base | awk -v "linenumber=$linenumber" 'NR==linenumber'
      return
      ;;
    'logs' | 'log' | 'l')
      op="logs"
      kc -n $ns $op $podname -f
      return
      ;;
    'describe' | 'des')
      op="describe"
      ;;
    *)
      op=$1
  esac

  kc -n $ns $op pod $podname
}

function xx() {
  if [ "$#" -ne 2 ]; then
    echo usage: xx "archive" "folder"
    return
  fi
  tar -C $2 -xvf $1
}

function cgz() {
  if [ "$#" -ne 2 ]; then
    echo usage: cgz sourcefolder filename
    return
  fi
    tar czf $2.tar.gz $1
}

function portf() {
        socat TCP-LISTEN:$1,fork TCP:$2:$3
}

rmproxy() {
    unset https_proxy
    unset http_proxy
    unset https_proxy
}

